#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sqlite3.h>
#include "sqlite3.h"
#include "tcp_server.h"

int tcp_init(int port, char* ip)
{
		//创建套节字
		int sockfd = socket(AF_INET, SOCK_STREAM, 0);
		if(sockfd==-1)
		return -1;
		//绑定套节字
		struct sockaddr_in addr;
		addr.sin_family = AF_INET;
   	 	addr.sin_port = htons(6666);
    	addr.sin_addr.s_addr = inet_addr(ip);
    	if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
    	return -1;
		//监听套节字
		if(listen(sockfd,4)==-1)
		return -1;
		printf("等待连接\n");
		
		return sockfd;
}

int tcp_request(int connfd)
{
	char buf[20];
	char name[50];
	char passwd[50];
	sqlite3 *db;
	read(connfd, buf, sizeof(buf));
	if(strcmp(buf,"login"))//
	{
		read(connfd, name, sizeof(name));
		read(connfd, passwd, sizeof(passwd));
		
		if(-1==user_login(name, passwd,db))
		{
			strcpy(buf,"登陆失败");
		}
		else
		{
			strcpy(buf,"登陆成功");
		}
		
		write(connfd, buf, sizeof(buf));
	}
	else if(strcmp(buf,"register"))//
	{
		read(connfd, name, sizeof(name));
		read(connfd, passwd, sizeof(passwd));
		
		if(-1==user_register(name, passwd,db))
		{
			strcpy(buf,"注册失败");
		}
		else
		{
			strcpy(buf,"注册成功");
		}
		
		write(connfd, buf, sizeof(buf));
	}
	else if(strcmp(buf,"update"))//
	{
		char oldname[50];
		read(connfd, name, sizeof(name));
		read(connfd, passwd, sizeof(passwd));
		read(connfd, oldname, sizeof(oldname));
		
		if(-1==user_update(name, passwd, oldname,db))
		{
			strcpy(buf,"更新失败");
		}
		else
		{
			strcpy(buf,"更新成功");
		}
		
		write(connfd, buf, sizeof(buf));
	}
	else if(strcmp(buf,"delete"))//
	{
		read(connfd, name, sizeof(name));
		read(connfd, passwd, sizeof(passwd));
		
		if(-1==user_delete(name, passwd,db))
		{
			strcpy(buf,"删除失败");
		}
		else
		{
			strcpy(buf,"删除成功");
		}
		
		write(connfd, buf, sizeof(buf));
	}
}







